import { drop } from 'lodash'
import React, { useRef, useState } from 'react'

const Index = () => {
  const [wrap, setwrap] = useState<any>([])
  const arr = useRef(null) as any

  const drop = (e: any) => {
    e.preventDefault();

    const res = arr.current?.getBoundingClientRect()
    if (!res) return
    const x = e.pageX - res.left - 60 / 2
    const y = e.pageY - res.top - 60 / 2
    const div = document.createElementNS('http://www.w3.org/2000/svg', "rect")
    div.setAttributeNS(null, 'width', "60")
    div.setAttributeNS(null, 'height', "60")
    div.setAttributeNS(null, 'x', `${x}`)
    div.setAttributeNS(null, 'y', `${y}`)

    setwrap((wrap: any) => [...wrap, {
      x: x,
      y: y,
      width: 60,
      height: 60,
      pid: +new Date
    }])

  }
  const dragover = (e: any) => {
    e.preventDefault();
  }

  console.log(wrap, '123456789')
  return (
    <div>
      <button draggable={true} onDragStart={(e) => {
        e.dataTransfer?.setData('Annie', "annie")
      }}>按钮</button>
      <svg ref={arr} style={{ width: '500px', height: '500px', background: 'pink' }} onDrop={drop} onDragOver={dragover}>
        {
          wrap && wrap.map((item: any) => {
            return <rect x={item.x} y={item.y} width={item.width} height={item.height}
              onMouseDown={() => {
                /**
                 * 鼠标按下时的处理函数。
                 * 
                 * 添加鼠标移动事件监听器，以实现拖动按钮时更新按钮位置的功能。
                 * 计算按钮新的top和left值，并通过dispatch调用editStyle动作处理器来更新按钮样式。
                 */
                const onmousemove = (e: any) => {
                  const obj = {
                    x: 0,
                    y: 0,
                    pid: item.pid,
                  }

                  //                           y: e.clientY - rect.top - 150 / 2
                  const res = arr.current?.getBoundingClientRect()
                  const index = wrap.findIndex((v: any) => v.pid == item.pid)
                  wrap[index] = {
                    ...wrap[index],
                    x: e.clientX - res.left - 60 / 2,
                    y: e.clientY - res.top - 60 / 2,
                  }
                  setwrap([...wrap])
                }
                document.addEventListener('mousemove', onmousemove);

                /**
                 * 鼠标松开时的处理函数。
                 * 
                 * 移除鼠标移动事件监听器，以停止更新按钮位置。
                 */
                onmouseup = () => {
                  document.removeEventListener('mousemove', onmousemove);
                }
              }
              }
            ></rect>
          })
        }
      </svg>
    </div>
  )
}

export default Index
